import sys

sys.path.append('../')

from config import *


def do_match(exp, edu, title, salary, desc, location, company, industry, brandUniversity):
    jd_token = extract_core_skills(desc)

    edu = '|'.join(re.split('[,，-]', edu))
    title = '|'.join(re.split('[,，-]', title))
    location = '|'.join(re.split('[,，-]', location))
    company = re.split('[,，-]', company)
    industry = '|'.join(re.split('[,，-]', industry))

    resumes = []

    for item in qushu_resume_coll.find({'personal_info.edu': {'$regex': edu, '$options': 'i'}, 'wanted_job.title': {'$regex': title, '$options': 'i'}, 'wanted_job.location': {'$regex': location, '$options': 'i'}}):
        if not 'token' in item:
            continue

        # 985/211匹配
        if brandUniversity == 'true':
            school_matched = False

            for se in item['edu_experience']:
                if se['school'].strip() in school_985_211:
                    school_matched = True

            if not school_matched:
                continue

        # 历史企业匹配
        if company:
            company_matched = False

            hist_comp = ' '.join([i['company'] for i in item['work_experience']])

            for c in company:
                if c in hist_comp:
                    company_matched = True

            if not company_matched:
                continue

        if exp:
            if not item['personal_info']['exp'].strip():
                continue

            job_exp = np.array(re.split('[,，-]', exp)).astype(int).tolist()  # list [4,6]

            if re.match('\d+', item['personal_info']['exp'].strip()):
                resume_exp = int(re.match('\d+', item['personal_info']['exp'].strip()).group())  # int 5

                if len(job_exp) == 1 and resume_exp < job_exp[0]:
                    continue

                if len(job_exp) == 2 and (resume_exp < min(job_exp) or resume_exp > max(job_exp)):
                    continue
            else:
                # 如果简历上没有关于工作经验的明确表示则过滤
                continue

        # 薪资过滤
        if salary:
            job_salary = np.array(re.split('[，,-]', salary)).astype(int).tolist()
            wanted_salary = salary_transfer(item['wanted_job']['salary'])

            print(job_salary, wanted_salary)

            if len(wanted_salary) and len(job_salary) and min(wanted_salary) > max(job_salary):
                continue

            if len(wanted_salary) and len(job_salary) and max(wanted_salary) < min(job_salary):
                continue

        item['jd_token'] = jd_token
        item['jd_company'] = company
        item['jd_industry'] = industry

        item['id'] = str(item['_id'])

        del item['_id']

        resumes.append(item)

    # 技能匹配度排序
    resumes.sort(key = skill_matching_ranking, reverse = True)

    result = []

    for r in resumes:
        repeated = False

        for item in result:
            if difflib.SequenceMatcher(None, r['self_introduce'], item['self_introduce']).ratio() > 0.9:
                repeated = True
                break

        if not repeated:
            result.append(r)

        if len(result) == 200:
            break

    # 历史企业匹配度排序
    # if company:
    #     result.sort(key = comp_matching_ranking, reverse = True)

    # 行业标签匹配度
    if industry:
        result.sort(key = industry_matching_ranking, reverse = True)

    return result


def industry_matching_ranking(item):
    jd_industry = item['jd_industry']
    score = 0

    for we in item['work_experience']:
        comp = itjuzi_coll.find_one({'fullname': we['company']})

        if comp and re.findall(jd_industry, ' '.join(comp['tagList'] + comp['tag_info'])):
            score += 1

    return score


def skill_matching_ranking(item):
    jd_token = item['jd_token']
    score = 0

    for w in jd_token:
        for i in item['token']:
            if w.lower() == i.lower():
                score += jd_token[w]
                break

    return score


def comp_matching_ranking(item):
    jd_company = item['jd_company']
    score = 0

    for we in item['work_experience']:
        if re.findall(jd_company, we['company'].strip()):
            score += 1

    return score


def doc_to_sents(doc):
    pat = '。|!|•|;|；||（\d{1,2}）|\(\d{1,2}\)|\d、|\d\.|xa0|●|||\\n|Ø|！|★'

    result = re.split(pat, doc)

    result = filter(lambda i: i and len(i) > 4, result)
    result = list(map(lambda i: i and re.sub('\\n', '', i).strip(':：').strip(), result))

    return result


stoplist = []


def token(desc):
    return [word for word, flag in pseg.cut(desc) if flag not in ['m', 'x'] and len(word) > 1 and word not in stoplist]


with open(os.path.join(os.getcwd(), 'core.txt'), 'r', encoding = 'utf-8') as file:
    techwords = [w.strip().lower() for w in file.readlines()]

    for w in techwords:
        jieba.add_word(w, 10000, 'n')


def extract_core_skills(desc):
    token = {w: 1 for w, f in pseg.cut(desc.lower()) if f in ['eng'] or w in techwords}

    return token


def salary_transfer(salary):
    if not salary.strip():
        return []

    if re.match('\d+[Kk]-\d+[Kk]', salary):
        salary = (np.array(re.findall('\d+', salary)).astype(int) * 1000).tolist()
    elif re.match('\d+[Kk]以上', salary):
        salary = (np.array(re.findall('\d+', salary)).astype(int) * 1000).tolist()
    elif re.match('\d+-\d+元/月', salary) or re.match('\d+以下元/月', salary) or re.match('\d+以上元/月', salary):
        salary = (np.array(re.findall('\d+', salary)).astype(int)).tolist()
    elif re.match('\d+-\d+元/年', salary) or re.match('\d+-\d+以下元/年', salary) or re.match('\d+-\d+以上元/年', salary):
        salary = (np.array(re.findall('\d+', salary)).astype(int) / 12).tolist()
    elif re.match('\d+-\d+万元/年', salary) or re.match('\d+-\d+以上万元/年', salary) or re.match('\d+-\d+以下万元/年', salary):
        salary = (np.array(re.findall('\d+', salary)).astype(int) * 10000 / 12).tolist()
    elif re.match('\d+万以下元/年', salary) or re.match('\d+万以上元/年', salary):
        salary = (np.array(re.findall('\d+', salary)).astype(int) * 10000 / 12).tolist()
    elif salary.strip() in ['面议', '保密', '不限']:
        salary = []
    elif re.match('\d+元/天', salary):
        salary = (np.array(re.findall('\d+', salary)).astype(int) * 30).tolist()
    else:
        salary = []

    return salary


@app.route('/industry_labels.do', methods = ['GET'])
def industry_labels():
    labels = list(set([label for item in itjuzi_coll.find() for label in item['tagList']]))

    resp = {
        'success': True,
        'data': labels
    }

    response = make_response(jsonify(resp))
    return response


@app.route('/resum_job_match/match.do', methods = ['GET'])
def match():
    if not 'username' in session:
        return redirect(url_for('login'))

    job_exp = request.args.get('exp', '').strip()
    job_edu = request.args.get('edu', '').strip().replace('专科', '大专')
    job_title = request.args.get('title', '').strip()
    job_salary = request.args.get('salary', '').strip()
    job_company = request.args.get('company', '').strip()
    job_desc = request.args.get('description', '').strip()
    job_location = request.args.get('location', '').strip()
    job_industry = request.args.get('industry', '').strip()
    brandUniversity = request.args.get('brandUniversity', '').strip()

    if not job_title:
        resp = {
            'success': False,
            'msg': '请指定岗位名称'
        }

        response = make_response(jsonify(resp))
        return response

    if not job_desc:
        resp = {
            'success': False,
            'msg': '职位具体描述不能为空'
        }

        response = make_response(jsonify(resp))
        return response

    if job_exp and not re.match('^\d+[,，-]\d+$', job_exp) and not re.match('^\d+$', job_exp):
        resp = {
            'success': False,
            'msg': '经验要求格式不合规~'
        }

        response = make_response(jsonify(resp))
        return response

    if job_salary and not re.match('^\d+[,，-]\d+$', job_salary) and not re.match('^\d+$', job_salary):
        resp = {
            'success': False,
            'msg': '薪资要求格式不合规~'
        }

        response = make_response(jsonify(resp))
        return response

    matched = do_match(job_exp, job_edu, job_title, job_salary, job_desc, job_location, job_company, job_industry, brandUniversity)

    # if job_company:
    #     job_company = re.split('[，,]', job_company)

    for item in matched:
        titles = [i for i in re.split('[\s，|]', item['wanted_job']['title']) if i.strip()]

        for t in titles:
            if job_title in t or t in job_title:
                item['wanted_job']['title'] = t
                break

        if re.findall('\d+', item['personal_info']['exp']):
            item['personal_info']['exp'] = re.findall('\d+', item['personal_info']['exp'])[0] + '年'
        else:
            item['personal_info']['exp'] = '-'

        item['personal_info']['age'] = re.sub('\\n', '', item['personal_info']['age']).strip()

        if not '男' in item['personal_info']['age'] and not '女' in item['personal_info']['age']:
            item['personal_info']['age'] = re.sub('（.+）', '', item['personal_info']['age']).strip()
        else:
            item['personal_info']['age'] = '-'

    for item in matched:
        if 'token' in item:
            del item['token']

        if 'jd_token' in item:
            del item['jd_token']

    resp = {
        'success': True,
        'matched': matched,
        'job_title': job_title,
        'job_desc': doc_to_sents(job_desc)
    }

    response = make_response(jsonify(resp))
    return response
